import { ref } from 'vue'
import { ElMessage, ElNotification } from 'element-plus'

/**
 * Electron增强通知系统
 * 支持原生系统通知和Web通知的统一接口
 */

// 通知类型
export type NotificationType = 'info' | 'success' | 'warning' | 'error'

// 通知选项
export interface NotificationOptions {
  title: string
  message: string
  type?: NotificationType
  duration?: number
  icon?: string
  silent?: boolean
  urgency?: 'normal' | 'critical' | 'low'
  actions?: Array<{
    type: string
    text: string
  }>
  onClick?: () => void
  onAction?: (actionType: string) => void
}

// 通知历史记录
export interface NotificationRecord {
  id: string
  title: string
  message: string
  type: NotificationType
  timestamp: Date
  read: boolean
}

export function useElectronNotification() {
  // 状态管理
  const isElectron = !!(window as any).electronAPI
  const notificationHistory = ref<NotificationRecord[]>([])
  const unreadCount = ref(0)

  /**
   * 显示通知
   */
  const showNotification = async (options: NotificationOptions) => {
    const {
      title,
      message,
      type = 'info',
      duration = 4500,
      icon,
      silent = false,
      urgency = 'normal',
      actions = [],
      onClick,
      onAction
    } = options

    // 添加到历史记录
    const record: NotificationRecord = {
      id: generateId(),
      title,
      message,
      type,
      timestamp: new Date(),
      read: false
    }
    
    notificationHistory.value.unshift(record)
    unreadCount.value++

    try {
      if (isElectron) {
        // 使用Electron原生通知
        await showElectronNotification({
          title,
          body: message,
          icon: icon || getDefaultIcon(type),
          silent,
          urgency,
          actions
        })
      } else {
        // 使用Web通知
        await showWebNotification({
          title,
          message,
          type,
          duration,
          onClick
        })
      }
    } catch (error) {
      console.error('通知显示失败:', error)
      // 降级到Element Plus通知
      showFallbackNotification({ title, message, type, duration })
    }
  }

  /**
   * 显示Electron原生通知
   */
  const showElectronNotification = async (options: any) => {
    const electronAPI = (window as any).electronAPI
    
    if (!electronAPI?.notification?.show) {
      throw new Error('Electron通知API不可用')
    }

    await electronAPI.notification.show(options)
  }

  /**
   * 显示Web通知
   */
  const showWebNotification = async (options: {
    title: string
    message: string
    type: NotificationType
    duration: number
    onClick?: () => void
  }) => {
    const { title, message, type, duration, onClick } = options

    // 检查通知权限
    if (Notification.permission === 'denied') {
      throw new Error('通知权限被拒绝')
    }

    if (Notification.permission === 'default') {
      const permission = await Notification.requestPermission()
      if (permission !== 'granted') {
        throw new Error('通知权限未授予')
      }
    }

    // 创建通知
    const notification = new Notification(title, {
      body: message,
      icon: getDefaultIcon(type),
      tag: 'rickpan-notification'
    })

    // 设置点击事件
    if (onClick) {
      notification.onclick = onClick
    }

    // 自动关闭
    setTimeout(() => {
      notification.close()
    }, duration)
  }

  /**
   * 显示降级通知（Element Plus）
   */
  const showFallbackNotification = (options: {
    title: string
    message: string
    type: NotificationType
    duration: number
  }) => {
    const { title, message, type, duration } = options

    ElNotification({
      title,
      message,
      type,
      duration,
      position: 'top-right'
    })
  }

  /**
   * 快捷通知方法
   */
  const notifySuccess = (title: string, message: string) => {
    return showNotification({ title, message, type: 'success' })
  }

  const notifyError = (title: string, message: string) => {
    return showNotification({ 
      title, 
      message, 
      type: 'error',
      urgency: 'critical',
      duration: 6000
    })
  }

  const notifyWarning = (title: string, message: string) => {
    return showNotification({ title, message, type: 'warning' })
  }

  const notifyInfo = (title: string, message: string) => {
    return showNotification({ title, message, type: 'info' })
  }

  /**
   * 文件上传完成通知
   */
  const notifyUploadComplete = (fileName: string, fileCount?: number) => {
    const title = '文件上传完成'
    const message = fileCount 
      ? `成功上传 ${fileCount} 个文件`
      : `文件 "${fileName}" 上传完成`

    return showNotification({
      title,
      message,
      type: 'success',
      actions: [
        { type: 'view', text: '查看文件' },
        { type: 'dismiss', text: '忽略' }
      ],
      onAction: (actionType) => {
        if (actionType === 'view') {
          // 跳转到文件列表
          window.location.hash = '/dashboard/files'
        }
      }
    })
  }

  /**
   * AI任务完成通知
   */
  const notifyAITaskComplete = (taskName: string, result?: string) => {
    const title = 'AI任务完成'
    const message = result 
      ? `${taskName} 已完成：${result}`
      : `${taskName} 处理完成`

    return showNotification({
      title,
      message,
      type: 'success',
      actions: [
        { type: 'view', text: '查看结果' },
        { type: 'dismiss', text: '忽略' }
      ],
      onAction: (actionType) => {
        if (actionType === 'view') {
          // 跳转到AI助手页面
          window.location.hash = '/dashboard/ai-chat'
        }
      }
    })
  }

  /**
   * 系统更新通知
   */
  const notifyUpdateAvailable = (version: string) => {
    return showNotification({
      title: '发现新版本',
      message: `RickPan ${version} 现已可用`,
      type: 'info',
      urgency: 'normal',
      duration: 0, // 不自动关闭
      actions: [
        { type: 'update', text: '立即更新' },
        { type: 'later', text: '稍后提醒' },
        { type: 'dismiss', text: '忽略' }
      ],
      onAction: (actionType) => {
        if (actionType === 'update') {
          // 触发更新
          if (isElectron) {
            const electronAPI = (window as any).electronAPI
            electronAPI.updater?.downloadUpdate()
          }
        }
      }
    })
  }

  /**
   * 获取默认图标
   */
  const getDefaultIcon = (type: NotificationType): string => {
    const iconMap = {
      success: '/icons/success.png',
      error: '/icons/error.png',
      warning: '/icons/warning.png',
      info: '/icons/info.png'
    }
    
    return iconMap[type] || iconMap.info
  }

  /**
   * 生成唯一ID
   */
  const generateId = (): string => {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  /**
   * 标记通知为已读
   */
  const markAsRead = (id: string) => {
    const notification = notificationHistory.value.find(n => n.id === id)
    if (notification && !notification.read) {
      notification.read = true
      unreadCount.value = Math.max(0, unreadCount.value - 1)
    }
  }

  /**
   * 标记所有通知为已读
   */
  const markAllAsRead = () => {
    notificationHistory.value.forEach(notification => {
      notification.read = true
    })
    unreadCount.value = 0
  }

  /**
   * 清空通知历史
   */
  const clearHistory = () => {
    notificationHistory.value = []
    unreadCount.value = 0
  }

  /**
   * 获取未读通知
   */
  const getUnreadNotifications = () => {
    return notificationHistory.value.filter(n => !n.read)
  }

  /**
   * 检查通知权限
   */
  const checkPermission = async (): Promise<boolean> => {
    if (isElectron) {
      // Electron环境默认有权限
      return true
    }

    if (!('Notification' in window)) {
      return false
    }

    if (Notification.permission === 'granted') {
      return true
    }

    if (Notification.permission === 'default') {
      const permission = await Notification.requestPermission()
      return permission === 'granted'
    }

    return false
  }

  /**
   * 请求通知权限
   */
  const requestPermission = async (): Promise<boolean> => {
    if (isElectron) {
      return true
    }

    if (!('Notification' in window)) {
      ElMessage.warning('当前浏览器不支持通知功能')
      return false
    }

    try {
      const permission = await Notification.requestPermission()
      if (permission === 'granted') {
        ElMessage.success('通知权限已授予')
        return true
      } else {
        ElMessage.warning('通知权限被拒绝')
        return false
      }
    } catch (error) {
      ElMessage.error('请求通知权限失败')
      return false
    }
  }

  return {
    // 状态
    isElectron,
    notificationHistory,
    unreadCount,

    // 基础方法
    showNotification,
    checkPermission,
    requestPermission,

    // 快捷方法
    notifySuccess,
    notifyError,
    notifyWarning,
    notifyInfo,

    // 业务通知
    notifyUploadComplete,
    notifyAITaskComplete,
    notifyUpdateAvailable,

    // 历史管理
    markAsRead,
    markAllAsRead,
    clearHistory,
    getUnreadNotifications
  }
}
